# -*- coding: utf-8 -*-
from sqlalchemy import create_engine, Column, String, DateTime, Integer, Float, func, JSON, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
#import redis

# 初始化数据库连接:
# engine = create_engine('mysql+pymysql://root:123asd@localhost:3306/utf_sys?charset=utf8')
engine = create_engine('postgresql+psycopg2://postgres:123asd@192.168.0.186/execdb')
# "mssql+pymssql://sa:123456@192.168.0.209:1433/AnToNio1.0?charset=utf8"


# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)

# 初始化redis数据库连接
#Redis = redis.StrictRedis(host='localhost',port=6379,db=0)

Base = declarative_base()




#做一个表记录搜索历史
class ArticleModel(Base):
    """
    参数说明：

    _id: 这个搜索项目的ID, （TODO：以后在数据库生成)
    province: 省
    city: 市
    zone: 区
    department: 文件所属部门
    title: 文章题目
    url: 原文链接
    status: 文章状态，active 有效, expired 过期，disabled 禁用
    content: 文章内容
    abstract: 文章摘要
    md5_check: 文章校验
    tags:标签
    publish_date: 发布时间
    expired_date: 过期时间
    created_at: 创建时间
    """

    __tablename__ = 'tab_articale'

    id = Column(Integer, primary_key=True)
    province = Column(String(10))
    city = Column(String(10))
    zone = Column(String(10))
    department = Column(String(20))
    title = Column(String(200))
    url = Column(String(200))
    status = Column(String(20), default='active')
    content = Column(Text)
    abstract = Column(Text)
    md5_check = Column(String(128))
    tags = Column(JSON, default=JSON.NULL)
    attachments = Column(JSON, default=JSON.NULL)
    publish_date = Column(DateTime)
    expired_date = Column(DateTime)
    created_at = Column(DateTime, server_default=func.now())


    def to_json(self):
        return {
            'id': self.id,
            'province': self.province,
            'city': self.city,
            'zone': self.zone,
            'department': self.department,
            'title': self.title,
            'url': self.url,
            'status': self.status,
            'abstract': self.abstract,
            'id': self.id,
            'tags': self.tags,
            'attachments': self.attachments,
            'publish_date': self.publish_date.strftime("%Y-%m-%d") if self.publish_date is not None else "",
            'expired_date': self.expired_date.strftime("%Y-%m-%d") if self.expired_date is not None else "", 
            'created_at': self.created_at.strftime("%Y-%m-%d %H:%M:%S") if self.created_at is not None else "",
        }




#创建数据表，如果数据表存在则忽视！！！
Base.metadata.create_all(engine)